const app = getApp()

Page({
  data: {
    id: '',
    product: {
      name: '',
      price: '',
      stock: '',
      description: '',
      images: [],
      category: '',
      status: 'on'
    },
    categories: ['食品', '饮品', '生活用品', '其他'],
    imageUrls: []
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ id: options.id })
      this.loadProduct(options.id)
    }
  },

  // 加载商品信息
  async loadProduct(id) {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('products').doc(id).get()
      
      this.setData({
        product: data,
        imageUrls: data.images || []
      })
    } catch (error) {
      console.error('加载商品信息失败：', error)
    }
  },

  // 输入框内容变化
  onInput(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`product.${field}`]: value
    })
  },

  // 选择分类
  onCategoryChange(e) {
    this.setData({
      'product.category': this.data.categories[e.detail.value]
    })
  },

  // 选择图片
  async chooseImage() {
    try {
      const res = await wx.chooseImage({
        count: 9,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      })

      const tempFilePaths = res.tempFilePaths
      wx.showLoading({ title: '上传中...' })

      const uploadTasks = tempFilePaths.map(filePath => {
        return wx.cloud.uploadFile({
          cloudPath: `products/${Date.now()}-${Math.floor(Math.random() * 1000)}${filePath.match(/\.[^.]+?$/)[0]}`,
          filePath
        })
      })

      const uploadResults = await Promise.all(uploadTasks)
      const newImageUrls = uploadResults.map(result => result.fileID)
      
      this.setData({
        imageUrls: [...this.data.imageUrls, ...newImageUrls],
        'product.images': [...this.data.imageUrls, ...newImageUrls]
      })

      wx.hideLoading()
    } catch (error) {
      console.error('选择/上传图片失败：', error)
      wx.hideLoading()
    }
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const imageUrls = this.data.imageUrls
    const fileID = imageUrls[index]

    wx.cloud.deleteFile({
      fileList: [fileID]
    })

    imageUrls.splice(index, 1)
    this.setData({
      imageUrls,
      'product.images': imageUrls
    })
  },

  // 保存商品
  async saveProduct() {
    const { product, id } = this.data
    
    // 表单验证
    if (!product.name || !product.price || !product.stock) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    try {
      wx.showLoading({ title: '保存中...' })
      const db = wx.cloud.database()
      
      if (id) {
        // 更新商品
        await db.collection('products').doc(id).update({
          data: {
            ...product,
            updateTime: db.serverDate()
          }
        })
      } else {
        // 新增商品
        await db.collection('products').add({
          data: {
            ...product,
            createTime: db.serverDate(),
            updateTime: db.serverDate()
          }
        })
      }

      wx.hideLoading()
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      })

      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    } catch (error) {
      console.error('保存商品失败：', error)
      wx.hideLoading()
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    }
  }
}) 